//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Net;
using System.Xml;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.ControlPanel.UI;
using CommunityServer.RssCtrl.Components;
using Rss;
using CommunityServer.Reader.Components;

namespace CommunityServer.ControlPanel.Tools
{
	/// <summary>
	/// Summary description for ManageIPAddresses.
	/// </summary>
	public class RssCtrlManage : BaseToolsPage
	{

		#region Members

		protected Label StatusMessage;
		protected CommunityServer.Controls.MPContent DescriptionRegion;
		protected CommunityServer.Controls.MPContent TaskRegion;
		protected CommunityServer.Controls.MPContainer MPContainer;
		protected CommunityServer.Controls.StatusMessage Status;
		protected CommunityServer.ControlPanel.Controls.ResourceControl RegionTitle;
        protected CommunityServer.ControlPanel.Controls.FormLabel FormlabelName;
        protected CommunityServer.ControlPanel.Controls.ResourceLinkButton CtrlSaveButton;
        protected CommunityServer.ControlPanel.Controls.ResourceLinkButton CtrlPurgeButton;
        protected ComponentArt.Web.UI.Grid gridFeeds;
        protected System.Web.UI.WebControls.Button Button1;
        protected TextBox CtrlTitle;
        protected TextBox PostCount;
        protected TextBox ExcerptSize;
        protected TextBox hiddenUniqueID;

        private int CtrlID;
        private CSContext context;
		#endregion

		override protected void OnInit(EventArgs e)
		{
			//this.Load += new EventHandler(this.Page_Load);
            CtrlSaveButton.Click += new EventHandler(CtrlSaveButton_Click);
            CtrlPurgeButton.Click += new EventHandler(CtrlPurgeButton_Click);
            InitializeComponent();
			base.OnInit(e);
		}

		private void Page_Load(object sender, EventArgs e)
		{
            context = CSContext.Current;
            CtrlID = context.GetIntFromQueryString("ctrlID", -1);
			if (!Page.IsPostBack) 
			{
                if (CtrlID != -1)
                {
                    this.CtrlBind();
                    LoadGrid();
                    gridFeeds.DataBind();
                }
                else
                    FormlabelName.Text = "Not Known";  // Can't be null so default to "Not Known"
			}
		}

        void CtrlSaveButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (CtrlID != -1)
                {
                    RssCtrl.RssCtrl ctrl = new CommunityServer.RssCtrl.RssCtrl();
                    ctrl.CtrlID = CtrlID;
                    ctrl.PostCount = Convert.ToInt32(PostCount.Text);
                    ctrl.Title = CtrlTitle.Text;
                    ctrl.ExerptSize = Convert.ToInt32(ExcerptSize.Text);

                    RssCtrl.Components.RssCtrls.Update(ctrl);
                    
                    ClearCache(); //Blow out the cache to force a refresh
                    
                    CtrlBind();
                    LoadGrid();
                    gridFeeds.DataBind();
                }
            }
            CtrlBind();
        }

        void CtrlPurgeButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (CtrlID != -1)
                {
                    RssCtrl.Components.RssCtrls.Purge(CtrlID);
                    ClearCache(); //Blow out the cache to force a refresh
                    
                    CtrlBind();
                    LoadGrid();
                    gridFeeds.DataBind();
                }
            }
            CtrlBind();
        }

	    private void ClearCache()
	    {
            string cacheKey = hiddenUniqueID.Text + CtrlID.ToString();
            CSCache.Remove(cacheKey); //Blow out the cache to force a refresh
        }
        private void CtrlBind()
		{
            RssCtrl.RssCtrl ctrl = RssCtrl.Components.RssCtrls.Get(CtrlID);
            //Repeater_RssCtrls.DataBind();
            if (ctrl.Name != null)
            {
                hiddenUniqueID.Text = ctrl.Name;
                FormlabelName.Text = ctrl.Name;
                CtrlTitle.Text = ctrl.Title;
                PostCount.Text = ctrl.PostCount.ToString();
                ExcerptSize.Text = ctrl.ExerptSize.ToString();
            }
        }

        private void LoadGrid()
        {
            gridFeeds.DataSource = RssCtrlFeeds.GetEnabledFeedsByCtrlID(CtrlID);
        }

        //Now same as Update
        //private void gridFeeds_InsertCommand(object sender, ComponentArt.Web.UI.GridItemEventArgs e)
        //{
        //    string url = e.Item["Url"].ToString();
        //    string title = e.Item["Title"].ToString();
        //    int controlID = CtrlID;

        //    RssCtrl.RssCtrlFeed rcf = new CommunityServer.RssCtrl.RssCtrlFeed();
        //    rcf.CtrlID = CtrlID;
        //    rcf.Url = ValidateUrl(url);
        //    rcf.Title = title;
        //    RssCtrl.RssCtrlDataProvider.AddRssCtrlFeed(rcf);
        //}

        private string ValidateUrl(String Url)
        {
            Url = Url.Trim().ToLower().Replace("&amp;", "&").Replace("#$camp@*amp;","&");
            RssCtrl.RssCtrlFeed rcf = new CommunityServer.RssCtrl.RssCtrlFeed();
            RssFeed rssFeed = null;

            try
            {
                rcf.Url = Url;
                rssFeed = RssFeed.Read(rcf.CreateRequest());
            }
            catch (WebException we)
            {
                CSException csEx = new CSException(CSExceptionType.UnknownError, "Unable to add RssCtrl feed", we);
                csEx.Log(CSContext.Current.SettingsID);
                throw new ApplicationException("Unable to add RssCtrl feed. Please double check the URL specified.");
            }
            catch (XmlException)
            {
                // Thrown when the target URL is not a valid RSS feed.
                // Here, we need to head down the route of doing autodiscovery.
                try
                {
                    string discoveredUrl = AutoDiscoverer.DiscoverFeedUrl(Url);

                    if (discoveredUrl != null)
                        rssFeed = RssFeed.Read(discoveredUrl);
                }
                catch (InvalidOperationException)
                {
                    throw new ApplicationException("Unable to add the RssCtrl feed. The feed specified appears to be incomplete. Please attempt to contact the site administrator.");
                }
            }


            // Sometimes no XmlException is thrown, but the RSS.NET component works fine. Let's 
            // try to do it one more time.
            if (rssFeed == null || rssFeed.Channels.Count <= 0)
            {
                string discoveredUrl = AutoDiscoverer.DiscoverFeedUrl(Url);

                if (discoveredUrl != null)
                    rssFeed = RssFeed.Read(discoveredUrl);
            }

            // Finally, let's do one last check and if nothing's there, we have to assume all tries failed.
            if (rssFeed == null || rssFeed.Channels.Count <= 0)
            {
                throw new ApplicationException("Unable to add the RssCtrl feed specified. Please double check the URL, insure it's a valid URL to an RSS feed and try again.");
            }

            return Url;
        }
        private void gridFeeds_UpdateCommand(object sender, ComponentArt.Web.UI.GridItemEventArgs e)
        {
            string url = e.Item["Url"].ToString();
            string title = e.Item["Title"].ToString();
            string siteUrl = e.Item["SiteUrl"].ToString();
            int intervalMinutes = Globals.SafeInt(e.Item["IntervalMinutes"].ToString(), 5);
            int controlID = CtrlID;
            
            RssCtrl.RssCtrlFeed rcf = new CommunityServer.RssCtrl.RssCtrlFeed();
            rcf.CtrlID = CtrlID;
            //clean the mess from Ajax and the CA control
            rcf.Url = ValidateUrl(url.Trim().ToLower().Replace("&amp;", "&").Replace("#$camp@*amp;","&"));
            rcf.Title = title;
            rcf.SiteUrl = siteUrl;
            rcf.IntervalMinutes = intervalMinutes;
            RssCtrlFeeds.AddFeed(rcf);
        }

        private void gridFeeds_DeleteCommand(object sender, ComponentArt.Web.UI.GridItemEventArgs e)
        {
            int UrlID = System.Int32.Parse(e.Item["UrlID"].ToString());
            int CtrlID = System.Int32.Parse(e.Item["CtrlID"].ToString());
            RssCtrl.RssCtrlFeed rcf = new CommunityServer.RssCtrl.RssCtrlFeed();
            rcf.CtrlID = CtrlID;
            rcf.UrlID = UrlID;
            RssCtrlFeeds.DeleteFeed(rcf);
        }

        public void OnNeedRebind(object sender, EventArgs oArgs)
        {
            gridFeeds.DataBind();
        }

        public void OnNeedDataSource(object sender, EventArgs oArgs)
        {
            LoadGrid();
        }

        public void OnPageChanged(object sender, ComponentArt.Web.UI.GridPageIndexChangedEventArgs oArgs)
        {
            gridFeeds.CurrentPageIndex = oArgs.NewIndex;
        }

        public void OnSort(object sender, ComponentArt.Web.UI.GridSortCommandEventArgs oArgs)
        {
            gridFeeds.Sort = oArgs.SortExpression;
        }


		#region Events

		/// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            hiddenUniqueID.Visible = false;
            this.Load += new System.EventHandler(this.Page_Load);
            gridFeeds.NeedRebind += new ComponentArt.Web.UI.Grid.NeedRebindEventHandler(OnNeedRebind);
            gridFeeds.NeedDataSource += new ComponentArt.Web.UI.Grid.NeedDataSourceEventHandler(OnNeedDataSource);
            gridFeeds.PageIndexChanged += new ComponentArt.Web.UI.Grid.PageIndexChangedEventHandler(OnPageChanged);
            gridFeeds.SortCommand += new ComponentArt.Web.UI.Grid.SortCommandEventHandler(OnSort);
            gridFeeds.UpdateCommand += new ComponentArt.Web.UI.Grid.GridItemEventHandler(this.gridFeeds_UpdateCommand);
            gridFeeds.DeleteCommand += new ComponentArt.Web.UI.Grid.GridItemEventHandler(this.gridFeeds_DeleteCommand);
            gridFeeds.InsertCommand += new ComponentArt.Web.UI.Grid.GridItemEventHandler(this.gridFeeds_UpdateCommand);
        }
        #endregion
	}
}
